<template>
  <view class="schedule-detail-page">
    <view class="page-header">
      <text class="page-title">排班详情</text>
      <view class="header-actions">
        <button class="btn btn-default" @click="handleBack">返回</button>
        <button class="btn btn-primary" @click="handleEdit">编辑</button>
        <button class="btn btn-danger" @click="handleDelete">删除</button>
      </view>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view v-else class="detail-content">
      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">排班信息</text>
          <view :class="['status-badge', parseInt(schedule.status) === 1 ? 'status-active' : 'status-inactive']">
            {{ parseInt(schedule.status) === 1 ? '正常' : '停班' }}
          </view>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">医生姓名</text>
            <text class="value">{{ doctorName || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">所属医院</text>
            <text class="value">{{ hospitalName || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">排班日期</text>
            <text class="value highlight">{{ schedule.schedule_date || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">工作时间</text>
            <text class="value">{{ schedule.start_time || '-' }} ~ {{ schedule.end_time || '-' }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">时间段长度</text>
            <text class="value">{{ schedule.slot_duration_minutes || 0 }} 分钟</text>
          </view>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">号源情况</text>
        </view>
        <view class="card-body">
          <view class="slots-summary">
            <view class="slot-item">
              <text class="slot-label">总号源</text>
              <text class="slot-value total">{{ schedule.total_slots || 0 }}</text>
            </view>
            <view class="slot-item">
              <text class="slot-label">已预约</text>
              <text class="slot-value booked">{{ schedule.booked_slots || 0 }}</text>
            </view>
            <view class="slot-item">
              <text class="slot-label">可用</text>
              <text class="slot-value available">{{ schedule.available_slots || 0 }}</text>
            </view>
          </view>
          
          <view class="progress-section">
            <view class="progress-label">
              <text>预约进度</text>
              <text>{{ bookingRate }}%</text>
            </view>
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: bookingRate + '%' }"></view>
            </view>
          </view>
        </view>
      </view>

      <view class="detail-card" v-if="schedule.remark">
        <view class="card-header">
          <text class="card-title">备注信息</text>
        </view>
        <view class="card-body">
          <text class="remark-text">{{ schedule.remark }}</text>
        </view>
      </view>

      <view class="detail-card">
        <view class="card-header">
          <text class="card-title">时间信息</text>
        </view>
        <view class="card-body">
          <view class="detail-row">
            <text class="label">创建时间</text>
            <text class="value">{{ formatTime(schedule.create_time) }}</text>
          </view>
          
          <view class="detail-row">
            <text class="label">更新时间</text>
            <text class="value">{{ formatTime(schedule.update_time) }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const loading = ref(true)
const scheduleId = ref('')
const doctorName = ref('')
const hospitalName = ref('')
const schedule = reactive({
  doctor_id: '',
  schedule_date: '',
  start_time: '',
  end_time: '',
  slot_duration_minutes: 0,
  total_slots: 0,
  booked_slots: 0,
  available_slots: 0,
  remark: '',
  status: 1,
  create_time: null,
  update_time: null
})

const bookingRate = computed(() => {
  if (schedule.total_slots === 0) return 0
  return Math.round((schedule.booked_slots / schedule.total_slots) * 100)
})

onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  scheduleId.value = currentPage.options.id || ''
  
  if (!scheduleId.value) {
    uni.showToast({ title: '缺少排班ID', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
    }, 1500)
    return
  }
  
  await loadScheduleData()
  loading.value = false
})

async function loadScheduleData() {
  try {
    // 使用云函数获取排班详情（已包含医生姓名和医院名称）
    const dhSchedules = uniCloud.importObject('dh-doctor_schedules')
    const result = await dhSchedules.getScheduleById(scheduleId.value)
    
    if (result.code === 200 && result.data) {
      Object.assign(schedule, result.data)
      doctorName.value = result.data.doctor_name || '未知医生'
      hospitalName.value = result.data.hospital_name || '未知医院'
    } else {
      throw new Error(result.message || '排班不存在')
    }
  } catch (err) {
    console.error('加载排班数据失败:', err)
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
    }, 1500)
  }
}

function formatTime(timestamp) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hour = String(date.getHours()).padStart(2, '0')
  const minute = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

function handleBack() {
  uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
}

function handleEdit() {
  uni.redirectTo({ url: `/pages/business/doctor_schedules/edit?id=${scheduleId.value}` })
}

function handleDelete() {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个排班吗？此操作不可撤销。',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          // 调用云对象方法软删除排班
          const doctorSchedulesObj = uniCloud.importObject('dh-doctor_schedules')
          const result = await doctorSchedulesObj.deleteSchedule(scheduleId.value, '详情页删除')
          uni.hideLoading()
          if (result.code === 200) {
            uni.showToast({ title: result.message || '删除成功', icon: 'success' })
          } else {
            uni.showToast({ title: result.message || '删除失败', icon: 'none' })
            return
          }
          setTimeout(() => {
            uni.redirectTo({ url: '/pages/business/doctor_schedules/list' })
          }, 1500)
        } catch (err) {
          console.error('删除失败:', err)
          uni.hideLoading()
          uni.showToast({ title: err.message || '删除失败', icon: 'none' })
        }
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.schedule-detail-page {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.page-header {
  background: #fff;
  padding: 30rpx 40rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 20rpx;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 16rpx;
  flex-wrap: wrap;
}

.btn {
  padding: 12rpx 24rpx;
  font-size: 28rpx;
  border-radius: 8rpx;
  border: none;
  white-space: nowrap;
  min-width: 100rpx;
  text-align: center;
  
  &.btn-default {
    background: #f5f5f5;
    color: #666;
  }
  
  &.btn-primary {
    background: #007aff;
    color: #fff;
  }
  
  &.btn-danger {
    background: #ff3b30;
    color: #fff;
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .btn {
    flex: 1;
    min-width: 0;
  }
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.detail-content {
  flex: 1;
  padding: 20rpx;
}

.detail-card {
  background: #fff;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.card-header {
  background: #fafafa;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.status-badge {
  padding: 8rpx 20rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  
  &.status-active {
    background: #e8f5e9;
    color: #2e7d32;
  }
  
  &.status-inactive {
    background: #ffebee;
    color: #c62828;
  }
}

.card-body {
  padding: 32rpx;
}

.detail-row {
  display: flex;
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  font-size: 28rpx;
  color: #999;
  min-width: 180rpx;
}

.value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  
  &.highlight {
    font-weight: bold;
    color: #007aff;
  }
}

.slots-summary {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
  padding: 30rpx 0;
  background: #f8f9fa;
  border-radius: 8rpx;
}

.slot-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.slot-label {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 12rpx;
}

.slot-value {
  font-size: 48rpx;
  font-weight: bold;
  
  &.total {
    color: #1976d2;
  }
  
  &.booked {
    color: #e65100;
  }
  
  &.available {
    color: #2e7d32;
  }
}

.progress-section {
  margin-top: 20rpx;
}

.progress-label {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.progress-bar {
  height: 24rpx;
  background: #e0e0e0;
  border-radius: 12rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(to right, #4caf50, #8bc34a);
  transition: width 0.3s ease;
}

.remark-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
}
</style>
